
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title><?php echo $attr['project_name']; ?></title>
<style type="text/css">
html,body {
	margin: 0;
	padding: 0;
	background-color: #f2f2f2;
}
body {
	padding-bottom:50px;
}
#resize {
	position: absolute;
	background-color: #333;
	cursor: se-resize;
	width: 10px;
	height: 10px;
  z-index: 9999;
}
#cvs {
	width:200px;
	height:100px;
  margin-top: 35px;
	background-color:#30D699;
	display: block;
	position: relative;
}
#cvs img {
	position: absolute;
  border:1px dashed transparent;
  margin:-1px;
	z-index: 10;
	/* For Opera and <= IE9, we need to add unselectable="on" attribute onto each element */
    /* Check this site for more details: http://help.dottoro.com/lhwdpnva.php */
    -moz-user-select: none; /* These user-select properties are inheritable, used to prevent text selection */
    -webkit-user-select: none;
    -ms-user-select: none; /* From IE10 only */
    user-select: none; /* Not valid CSS yet, as of July 2012 */

    -webkit-user-drag: none; /* Prevents dragging of images/divs etc */
    user-drag: none;
  cursor:pointer;
}


#info {
  color:#A00;
}

.button {
  display: inline-block;
  margin-bottom: 0;
  font-weight: normal;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  border: 1px solid transparent;
  white-space: nowrap;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  border-radius: 4px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.button:focus,
.button:active:focus,
.button.active:focus {
  outline: thin dotted;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}
.button:hover,
.button:focus {
  color: #333333;
  text-decoration: none;
}
.button:active,
.button.active {
  outline: 0;
  background-image: none;
  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
  box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.button.disabled,
.button[disabled],
fieldset[disabled] .btn {
  cursor: not-allowed;
  pointer-events: none;
  opacity: 0.65;
  filter: alpha(opacity=65);
  -webkit-box-shadow: none;
  box-shadow: none;
}
.btn-white {
  color: #333333;
  background-color: #ffffff;
  border-color: #cccccc;
}
.btn-white:hover,
.btn-white:focus,
.btn-white:active,
.btn-white.active,
.open .dropdown-toggle.btn-white {
  color: #333333;
  background-color: #ebebeb;
  border-color: #adadad;
}
.btn-white:active,
.btn-white.active,
.open .dropdown-toggle.btn-white {
  background-image: none;
}
.btn-white.disabled,
.btn-white[disabled],
fieldset[disabled] .btn-white,
.btn-white.disabled:hover,
.btn-white[disabled]:hover,
fieldset[disabled] .btn-white:hover,
.btn-white.disabled:focus,
.btn-white[disabled]:focus,
fieldset[disabled] .btn-white:focus,
.btn-white.disabled:active,
.btn-white[disabled]:active,
fieldset[disabled] .btn-white:active,
.btn-white.disabled.active,
.btn-white[disabled].active,
fieldset[disabled] .btn-white.active {
  background-color: #ffffff;
  border-color: #cccccc;
}
.btn-white .badge {
  color: #ffffff;
  background-color: #333333;
}
.btn-blue {
  color: #ffffff;
  background-color: #428bca;
  border-color: #357ebd;
}
.btn-blue:hover,
.btn-blue:focus,
.btn-blue:active,
.btn-blue.active,
.open .dropdown-toggle.btn-blue {
  color: #ffffff;
  background-color: #3276b1;
  border-color: #285e8e;
}
.btn-blue:active,
.btn-blue.active,
.open .dropdown-toggle.btn-blue {
  background-image: none;
}
.btn-blue.disabled,
.btn-blue[disabled],
fieldset[disabled] .btn-blue,
.btn-blue.disabled:hover,
.btn-blue[disabled]:hover,
fieldset[disabled] .btn-blue:hover,
.btn-blue.disabled:focus,
.btn-blue[disabled]:focus,
fieldset[disabled] .btn-blue:focus,
.btn-blue.disabled:active,
.btn-blue[disabled]:active,
fieldset[disabled] .btn-blue:active,
.btn-blue.disabled.active,
.btn-blue[disabled].active,
fieldset[disabled] .btn-blue.active {
  background-color: #428bca;
  border-color: #357ebd;
}
.btn-blue .badge {
  color: #428bca;
  background-color: #ffffff;
}
.btn-green {
  color: #ffffff;
  background-color: #5cb85c;
  border-color: #4cae4c;
}
.btn-green:hover,
.btn-green:focus,
.btn-green:active,
.btn-green.active,
.open .dropdown-toggle.btn-green {
  color: #ffffff;
  background-color: #47a447;
  border-color: #398439;
}
.btn-green:active,
.btn-green.active,
.open .dropdown-toggle.btn-green {
  background-image: none;
}
.btn-green.disabled,
.btn-green[disabled],
fieldset[disabled] .btn-green,
.btn-green.disabled:hover,
.btn-green[disabled]:hover,
fieldset[disabled] .btn-green:hover,
.btn-green.disabled:focus,
.btn-green[disabled]:focus,
fieldset[disabled] .btn-green:focus,
.btn-green.disabled:active,
.btn-green[disabled]:active,
fieldset[disabled] .btn-green:active,
.btn-green.disabled.active,
.btn-green[disabled].active,
fieldset[disabled] .btn-green.active {
  background-color: #5cb85c;
  border-color: #4cae4c;
}
.btn-green .badge {
  color: #5cb85c;
  background-color: #ffffff;
}
.btn-light-blue {
  color: #ffffff;
  background-color: #5bc0de;
  border-color: #46b8da;
}
.btn-light-blue:hover,
.btn-light-blue:focus,
.btn-light-blue:active,
.btn-light-blue.active,
.open .dropdown-toggle.btn-light-blue {
  color: #ffffff;
  background-color: #39b3d7;
  border-color: #269abc;
}
.btn-light-blue:active,
.btn-light-blue.active,
.open .dropdown-toggle.btn-light-blue {
  background-image: none;
}
.btn-light-blue.disabled,
.btn-light-blue[disabled],
fieldset[disabled] .btn-light-blue,
.btn-light-blue.disabled:hover,
.btn-light-blue[disabled]:hover,
fieldset[disabled] .btn-light-blue:hover,
.btn-light-blue.disabled:focus,
.btn-light-blue[disabled]:focus,
fieldset[disabled] .btn-light-blue:focus,
.btn-light-blue.disabled:active,
.btn-light-blue[disabled]:active,
fieldset[disabled] .btn-light-blue:active,
.btn-light-blue.disabled.active,
.btn-light-blue[disabled].active,
fieldset[disabled] .btn-light-blue.active {
  background-color: #5bc0de;
  border-color: #46b8da;
}
.btn-light-blue .badge {
  color: #5bc0de;
  background-color: #ffffff;
}
.btn-orange {
  color: #ffffff;
  background-color: #f0ad4e;
  border-color: #eea236;
}
.btn-orange:hover,
.btn-orange:focus,
.btn-orange:active,
.btn-orange.active,
.open .dropdown-toggle.btn-orange {
  color: #ffffff;
  background-color: #ed9c28;
  border-color: #d58512;
}
.btn-orange:active,
.btn-orange.active,
.open .dropdown-toggle.btn-orange {
  background-image: none;
}
.btn-orange.disabled,
.btn-orange[disabled],
fieldset[disabled] .btn-orange,
.btn-orange.disabled:hover,
.btn-orange[disabled]:hover,
fieldset[disabled] .btn-orange:hover,
.btn-orange.disabled:focus,
.btn-orange[disabled]:focus,
fieldset[disabled] .btn-orange:focus,
.btn-orange.disabled:active,
.btn-orange[disabled]:active,
fieldset[disabled] .btn-orange:active,
.btn-orange.disabled.active,
.btn-orange[disabled].active,
fieldset[disabled] .btn-orange.active {
  background-color: #f0ad4e;
  border-color: #eea236;
}
.btn-orange .badge {
  color: #f0ad4e;
  background-color: #ffffff;
}
.btn-red {
  color: #ffffff;
  background-color: #d9534f;
  border-color: #d43f3a;
}
.btn-red:hover,
.btn-red:focus,
.btn-red:active,
.btn-red.active,
.open .dropdown-toggle.btn-red {
  color: #ffffff;
  background-color: #d2322d;
  border-color: #ac2925;
}
.btn-red:active,
.btn-red.active,
.open .dropdown-toggle.btn-red {
  background-image: none;
}
.btn-red.disabled,
.btn-red[disabled],
fieldset[disabled] .btn-red,
.btn-red.disabled:hover,
.btn-red[disabled]:hover,
fieldset[disabled] .btn-red:hover,
.btn-red.disabled:focus,
.btn-red[disabled]:focus,
fieldset[disabled] .btn-red:focus,
.btn-red.disabled:active,
.btn-red[disabled]:active,
fieldset[disabled] .btn-red:active,
.btn-red.disabled.active,
.btn-red[disabled].active,
fieldset[disabled] .btn-red.active {
  background-color: #d9534f;
  border-color: #d43f3a;
}
.btn-red .badge {
  color: #d9534f;
  background-color: #ffffff;
}
.btn-none {
  color: #428bca;
  font-weight: normal;
  cursor: pointer;
  border-radius: 0;
}
.btn-none,
.btn-none:active,
.btn-none[disabled],
fieldset[disabled] .btn-none {
  background-color: transparent;
  -webkit-box-shadow: none;
  box-shadow: none;
}
.btn-none,
.btn-none:hover,
.btn-none:focus,
.btn-none:active {
  border-color: transparent;
}
.btn-none:hover,
.btn-none:focus {
  color: #2a6496;
  text-decoration: underline;
  background-color: transparent;
}
.btn-none[disabled]:hover,
fieldset[disabled] .btn-none:hover,
.btn-none[disabled]:focus,
fieldset[disabled] .btn-none:focus {
  color: #999999;
  text-decoration: none;
}
.btn-big {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}
.btn-normal {
  padding: 5px 10px;
  font-size: 12px;
  line-height: 1.5;
  border-radius: 3px;
}
.btn-small {
  padding: 1px 5px;
  font-size: 12px;
  line-height: 1.5;
  border-radius: 3px;
}
</style>
<script type="text/javascript" src="http://html.zmaitech.com/document/common/z.js"></script>
<script type="text/javascript">
var json = <?php echo $attr['json'] ?>;
var id,selectedElm,tzdragg = function(){
	return {
	    move : function(evt){
	    	evt = evt || window.event;
	            var posX = evt.clientX,
	                posY = evt.clientY,
	                aX = posX - tzdragg.diffX,
	                aY = posY - tzdragg.diffY;
	        
		      if(id=='#resize'){
      			$('#cvs').css({
      				'width':aX+'px',
      				'height':(aY-35)+'px',
      			});
		      }else{
            var offX = parseInt($('#cvs').css('width'))-parseInt($(id).css('width'));
            var offY = parseInt($('#cvs').css('height'))-parseInt($(id).css('height'));
            aX = Math.min(offX,Math.max(0,aX));
            aY = Math.min(offY,Math.max(0,aY));
          }
          $(id).style.left = aX + 'px';
          $(id).style.top = aY + 'px';
          $('#info').html('background-position:'+(0-aX)+'px '+(0-aY)+'px');
	    },
	    startMoving : function(evt){
	        evt = evt || window.event;
	        id = '#'+this.id;

	    
	        var posX = evt.clientX,
	            posY = evt.clientY,
	            a = $(id),
	        divTop = a.style.top,
	        divLeft = a.style.left;
	        divTop = divTop.replace('px','');
	        divLeft = divLeft.replace('px','');
	        tzdragg.diffX = posX - divLeft,
	        tzdragg.diffY = posY - divTop;
	        $(document).on('mousemove',tzdragg.move);
	    }
	}
}();

</script>

</head>
<body>
<div id="xy" style="position:fixed;right:0px;bottom:0px;z-index:9999;padding:0 10px;"></div>
<div style="padding:5px 0;text-indent:5px;height:25px;position:fixed;left:0;top:0;z-index:9998;background-color:#FFF;width:100%;"><input type="file" accept="image/png" multiple="multiple" onchange="uploadFile(this,'<?php echo base_url('canvas/addImage/'.$attr['project_id']);?>');"/>
  <button onclick="onSave();" id="saveBtn" class="button btn-white btn-small">保存</button>
<span id="info"></span>
</div>
<div id="cvs" style="width:<?php  echo $attr['width'] ?>px;height:<?php  echo $attr['height'] ?>px;"></div>
<div id="resize"></div>
<script type="text/javascript">
$('#resize').css({
	left:$('#cvs').css('width'),
	top:35+parseInt($('#cvs').css('height'))+'px'
}).on('mousedown',tzdragg.startMoving).on('mouseup',function(event){
	$(document).un('mousemove',tzdragg.move);
});
$(document).on('mouseup',function(e){
	$(document).un('mousemove',tzdragg.move);
});



function onSave() {
  var imgs = $('#cvs').getElementsByTagName('img');
  var params = {project_id:<?php echo $attr['project_id'] ?>,width:parseInt($('#cvs').css('width')),height:parseInt($('#cvs').css('height'))};
  for(var i=0,len = imgs.length;i < len;i++) {
    var img = imgs[i];
    var id = getSpriteId(img);
    params['sprite['+i+'][sprite_id]'] = id;
    params['sprite['+i+'][sprite_x]'] = parseInt(img.style.left);
    params['sprite['+i+'][sprite_y]'] = parseInt(img.style.top);
    params['sprite['+i+'][sprite_status]'] = 1;
  }
  $.ajax({
    url:"<?php echo base_url('canvas/saveSprite'); ?>",
    params:params,
    success:function(res) {
      alert('保存成功!');
    }
  });
}

function uploadFile(el,url) {
  var passed = true;
    for(var index=0; index<el.files.length; index++){
      var File = el.files[index];
      if(File.type!="image/png"){
        passed = false;
      }
    }

    if(el.files.length==0){
      return;
    }

    if(!passed){
      alert('请上传png图片');
      return;
    }

    var xhrs = [], xhrimages = [];

    for(var index=0; index<el.files.length; index++){
      var File = el.files[index];

      xhrs[index] = new XMLHttpRequest();
      xhrs[index].index = index;
      xhrs[index].open('post', url, true);
      xhrs[index].setRequestHeader("Content-Type", "application/octet-stream");
      xhrs[index].setRequestHeader("X-FILENAME", encodeURI(File.name)||'file');
      xhrs[index].setRequestHeader("X-File-Size", File.fileSize);
      xhrs[index].setRequestHeader("X-File-Type", File.type);
      
      xhrs[index].onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200){
          var r = {};
          try {
            r = eval("(" + this.responseText + ")");
          } catch(err){}
          if(r.success){
            xhrimages[this.index]=r.addon.sprite_url;
            addImage(r.addon);
            // if(xhrs.length==xhrimages.length){
            //     addImage(r.addon);
            // }
          }else{
            alert(r.detail);
          }
        }
      };
      if ('getAsBinary' in File){
        xhrs[index].sendAsBinary(File.getAsBinary());
      }else{
        xhrs[index].send(File);
      }
  }
}


for(var i=0; i<json.length; i++){
	addImage(json[i]);
}

function addImage(item) {
  if(item.existed) {
    $('#__s'+item.sprite_id).src = item.sprite_url+'?'+(new Date().valueOf());
    return;
  }
  item.sprite_x = item.sprite_x||0;
  item.sprite_y = item.sprite_y||0;
  var img = new Image();
    img.src = item.sprite_url;
    img.style.left = item.sprite_x+'px';
    img.style.top = item.sprite_y+'px';
    //img.title = 'background-position:-'+item.sprite_x+'px -'+item.sprite_y+'px';
    img.title = item.sprite_name+'\n\n'+img.width+' x '+img.height;
    img.ondragstart = function() { return false; };

    img.id = '__s'+item.sprite_id;
    img.alt = item.sprite_name;
    
    $('#cvs').appendChild(img);
    $('#__s'+item.sprite_id).on('mousedown',function(e) {
        if(selectedElm==$(this)) {
          tzdragg.startMoving.call(this,e);
        }else if(selectedElm) { 
          selectedElm.css('border-color','transparent');
        }
    }).on('mouseup',function(e){
      $(document).un('mousemove',tzdragg.move);
    }).on('click',function(){
      selectedElm = $(this);
      $(this).css('border-color','#111');

      $('#info').html('background-position:'+(0-parseInt($(this).css('left')))+'px '+(0-parseInt($(this).css('top')))+'px');
    }).on('dblclick',function(e){
      html = 'background:transparent url(/uploads/<?php echo $attr['project_code']; ?>/sprite.png) no-repeat '+(0-parseInt($(this).css('left')))+'px '+(0-parseInt($(this).css('top')))+'px;';
      
      window.parent.spriteCSS(html);
    });
   
}


function getSpriteId(el) {
  var id = el.id.substring(3);
  return id;
}
$('#cvs').on('mousemove',function(evt){
  $('#xy').html('x:'+evt.clientX+' y:'+(evt.clientY-35))
});
document.onkeydown = function(event) {
     if (!event)
          event = window.event;
     var code = event.keyCode;
     if (event.charCode && code == 0)
          code = event.charCode;


      if(!selectedElm) return;

        var left = parseInt(selectedElm.css('left')),top = parseInt(selectedElm.css('top'));
      var move = true;
        switch (code) {
          case 37:  // left
          case 63234:
            left -= 1;

            break;
          case 38:  // up
          case 63232:
            top -= 1;
            break;
          case 39:  // right
          case 63235:
            left += 1;
            break;
          case 40:  // down
          case 63233:
            top += 1;
            break;
          case 46:  // delete
          case 8:
            if(confirm('确定要删除图片'+selectedElm.alt+'?')) {
              var id = getSpriteId(selectedElm);
              $.ajax({
                url:"<?php echo base_url('canvas/deleteSprite'); ?>",
                params:{'sprite_id':id},
                success:function(res) {
                  alert('删除成功!');
                }
              });
              $(selectedElm).remove();
            }
          break;
          default:
        move= false;
          break;
        }
   
      if(move) {
        var offX = parseInt($('#cvs').css('width'))-parseInt(selectedElm.css('width'));
        var offY = parseInt($('#cvs').css('height'))-parseInt(selectedElm.css('height'));
        left = Math.min(offX,Math.max(0,left));
        top = Math.min(offY,Math.max(0,top));

          selectedElm.css({'left':left+'px','top':top+'px'});
          $('#info').html('background-position:'+(0-left)+'px '+(0-top)+'px');

          if (event.preventDefault)
            event.preventDefault();
      }
      
};

$(window).on("keydown", function(e) {
  if (e.keyCode == 83 && (e.metaKey || e.ctrlKey)) {
    e.preventDefault();
    onSave();
  }
});
</script>
</body>
</html>
